<template>
  <el-form :inline="true" @submit.native.prevent>
    <el-form-item>
      <el-select v-model="submitData.supplierId" clearable
                 placeholder="请选择供应商">
        <el-option v-for="item in supplierList"
                   :key="item.id"
                   :label="item.name"
                   :value="item.id"/>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-select v-model="submitData.kUid" placeholder="选择采购人"
                 filterable clearable>
        <template #label="{ label }">
          采购人: <b v-text="label"/>
        </template>
        <el-option v-for="item in userList"
                   :key="item.id"
                   :label="item.nickName"
                   :value="item.id"/>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-select v-model="submitData.kAid" placeholder="选择操作人"
                 filterable clearable>
        <template #label="{ label }">
          操作人: <b v-text="label"/>
        </template>
        <el-option v-for="item in userList"
                   :key="item.id"
                   :label="item.nickName"
                   :value="item.id"/>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-select v-model="submitData.shopId" placeholder="选择店铺" style="width: 200px" clearable>
        <template #label="{ label,value }">
          店铺: <b v-text="label"/>
        </template>
        <el-option v-for="{id,shopName} in user.shopList"
                   :key="id"
                   :label="shopName"
                   :value="id"/>
      </el-select>
    </el-form-item>

    <el-table :data="tableData" v-loading="loading" border height="calc(100vh - 310px)">
      <el-table-column label="操作" width="80" align="center">
        <template #default="scope">
          <el-row justify="center">
            <el-icon size="20px" style="cursor: pointer">
              <Delete @click="tableData.splice(scope.$index,1)"/>
            </el-icon>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="序号" type="index" width="80" align="center"/>
      <el-table-column label="串号" prop="serialnumber" min-width="160" align="center">
        <template #default="scope">
          <el-input v-model="scope.row.serialnumber" :ref="`number${scope.$index}`" placeholder="请输入串号/回车"
                    @keydown.enter="inputEnter(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column label="产品名称" prop="paId" min-width="200" align="center">
        <template #default="{row}">
          <el-select v-model="row.paId"
                     filterable remote reserve-keyword
                     placeholder="请输入商品名称/串号搜索"
                     @change="(value) => handleChange(value, row)"
                     :remote-method="(query) => loadGoodsList(query, row)">
            <el-option v-for="goods in row.goodsList"
                       :value="goods.paId" :key="goods.paId" :label="goods.pname"
                       :disabled="!!tableData.find(i=>i.paId === goods.paId && row.paId !== goods.paId)"/>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="零售价" prop="lsPrice" width="100" align="center">
        <template #default="{row}">
          <el-input v-model="row.lsPrice" :disabled="!row.paId > 0"/>
        </template>
      </el-table-column>
      <el-table-column label="会员价" prop="hyPrice" width="100" align="center">
        <template #default="{row}">
          <el-input v-model="row.hyPrice" :disabled="!row.paId > 0"/>
        </template>
      </el-table-column>
      <el-table-column label="批发价" prop="pfPrice" width="100" align="center">
        <template #default="{row}">
          <el-input v-model="row.pfPrice" :disabled="!row.paId > 0"/>
        </template>
      </el-table-column>
      <el-table-column label="上次进价" prop="lastInPrice" width="100" align="center">
        <template #default="{row}">
          <el-input v-model="row.lastInPrice" disabled/>
        </template>
      </el-table-column>
      <el-table-column label="当前库存" prop="stockNumber" width="100" align="center">
        <template #default="{row}">
          <el-input v-model="row.stockNumber" disabled/>
        </template>
      </el-table-column>
      <el-table-column label="进货数量" prop="name" width="100" align="center">
        <template #default="{row}">
          <el-input v-model="row.number" :disabled="!row.paId > 0"/>
        </template>
      </el-table-column>
      <el-table-column label="进货价" prop="name" width="100" align="center">
        <template #default="{row}">
          <el-input v-model.number="row.price" :disabled="!row.paId > 0"/>
        </template>
      </el-table-column>
      <el-table-column label="小计" prop="name" width="100" align="center">
        <template #default="{row}">
          <el-input :value="row.number * row.price || 0" disabled/>
        </template>
      </el-table-column>
      <el-table-column label="备注说明" prop="remark" min-width="120" align="center">
        <template #default="{row}">
          <el-input v-model="row.conuent" :disabled="!row.paId > 0"/>
        </template>
      </el-table-column>
    </el-table>
    <el-row style="margin-top: 10px">
      <el-form-item label="合计数量">
        <b v-text="this.submitData.kNum"/>
      </el-form-item>
      <el-form-item label="合计金额">
        <b v-text="formatRMB(this.submitData.kPrice)"/>
      </el-form-item>
      <el-form-item>
        <el-input v-model="this.submitData.kText" placeholder="请输入进货备注" style="width: 260px"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit(1)">提交</el-button>
        <el-button type="warning" @click="submit(2)">提交不结算</el-button>
        <el-button type="success" @click="saveTemp">暂存草稿</el-button>
        <el-button type="success" @click="showTemp" :disabled="tempStatus">加载草稿</el-button>
      </el-form-item>
    </el-row>
  </el-form>
</template>

<script lang="ts">
import brandListDetail from "@/components/goods/brandListDetail.vue";
import userApi from "@/api/user";
import partsApi from "@/api/parts";
import supplierApi from "@/api/supplier";
import base from "@/utils/base";

export default {
  name: "brandList",
  components: {brandListDetail},
  mixins: [base],
  data() {
    let defaultItem = {
      serialnumber: "",
      paId: "",
      pname: "",
      lsPrice: "",
      hyPrice: "",
      price: 0,
      number: 1,
      conuent: ""
    }
    return {
      user: {},
      userList: [],
      supplierList: [],
      goodsList: [],
      submitData: {
        k_sn: "",//订单号
        kNum: 0,//总数量
        kPrice: 0,//总价
        k_status: "",//是否结算 1是 2否 3部分 4退回 5欠款
        k_zfprice: "",//支付金额
        k_syprice: "",//剩余金额
        k_type: "",//结算方式和金额
        kAid: "",//操作人
        kUid: "",//销售人 采购人
        kJxstatus: 1, // 进货
        kSfsj: 2, //2 配件入库
        supplierId: "",
        shopId: 0,
        kHsrid: "", //采购人
        kText: "",//备注
        kJhdzyf: "" //进货运费
      },
      item: defaultItem,
      tableData: [{
        serialnumber: "",
        paId: "",
        pname: "",
        lsPrice: "",
        hyPrice: "",
        price: 0,
        number: 1,
        conuent: "",
      }],
      loading: false,
      tempStatus: false
    };
  },
  watch: {
    tableData: {
      handler: function (newVal) {
        let haveNull = newVal.find(i => i.serialnumber === '')
        if (!haveNull) {
          this.$nextTick(() => {
            this.tableData.push({...this.item})
          })
        }
        this.submitData.kNum = this.tableData.filter(i => i.paId).reduce((sum, goods) => sum + (Number(goods.number) || 0), 0).toFixed(0);
        this.submitData.kPrice = this.tableData.filter(i => i.paId).reduce((sum, goods) => sum + (Number(goods.number || 0) * Number(goods.price || 0)), 0).toFixed(2);
      },
      deep: true
    },
  },
  created() {
    this.loadUser()
    this.loadSeller()
    this.loadSupplier()
    this.refreshTemp()
  },
  methods: {
    loadUser() {
      userApi.mine().then(({data}) => {
        this.user = data
        this.submitData.kUid = data.id;
        this.submitData.kAid = data.id;
        this.submitData.shopId = Number(this.currentShop);
      });
    },
    loadSeller() {
      userApi.sellerList().then(res => this.userList = res.data)
    },
    loadSupplier() {
      supplierApi.supplierList({page: 1, limit: 100, byLan: true, status: 1}).then(res => {
        this.supplierList = res.data.list
      })
    },
    loadGoodsList(keyword, row) {
      return new Promise((resolve, reject) => {
        if (!keyword) {
          resolve([])
          return
        }
        partsApi.partsList({keyword, byLan: true}).then(res => {
          row.goodsList = res.data.list
          resolve(res.data.list || [])
        }).catch(error => {
          reject(error)
        })
      })
    },
    handleChange(id, row) {
      let current = row.goodsList.find(i => i.paId === id);
      if (current.lastInPrice) {
        current.price = current.lastInPrice
      }
      Object.assign(row, current);
    },
    inputEnter(row) {
      /* 如果相同存在，数量+1 */
      let isHave = this.tableData.find(i => i.serialnumber === row.serialnumber);
      if (isHave.paId) {
        isHave.number = isHave.number + 1
        row.serialnumber = ''
        return
      }
      this.loadGoodsList(row.serialnumber, row).then(res => {
        if (res.length > 0) {
          this.handleChange(res[0].paId, row)
        }
      })
      this.$nextTick(() => {
        let next = this.$refs[`number${this.tableData.length - 1}`]
        next.focus()
      })
    },
    submit(type) {
      let list = this.tableData
          .filter(i => i.paId && i.number > 0 && i.price > 0)
          .map(goods => {
            return {
              ...goods,
              supplierId: this.submitData.supplierId,
              cgfId: this.submitData.supplierId,
              shopId: this.submitData.shopId,
              userId: this.submitData.kAid
            }
          })
      if (list.length <= 0) {
        return ElMessage.warning("没有可提交的数据")
      }
      console.log(list)
      let data = {
        ...this.submitData,
        list: list
      }
      switch (type) {
        case 1:
          this.clearTemp()
          console.log('submit', data)
          return ElMessage.success("提交")
        case 0:
          this.clearTemp()
          console.log('submit', data)
          return ElMessage.success("提交未结算")
      }
    },
    refreshTemp() {
      this.tempStatus = !window.localStorage.getItem(`purchase${this.currentShop}submitData`)
    },
    saveTemp() {
      window.localStorage.setItem(`purchase${this.currentShop}tableData`, JSON.stringify(this.tableData))
      window.localStorage.setItem(`purchase${this.currentShop}submitData`, JSON.stringify(this.submitData))
      this.refreshTemp()
      return ElMessage.success("暂存成功")
    },
    showTemp() {
      let submitData = window.localStorage.getItem(`purchase${this.currentShop}submitData`)
      if (submitData) {
        this.submitData = JSON.parse(submitData)
      }
      let tableData = window.localStorage.getItem(`purchase${this.currentShop}tableData`);
      if (tableData) {
        this.tableData = JSON.parse(tableData)
      }
      this.refreshTemp()
      ElMessage.success("加载成功")
    },
    clearTemp() {
      window.localStorage.removeItem(`purchase${this.currentShop}tableData`)
      window.localStorage.removeItem(`purchase${this.currentShop}submitData`)
      this.refreshTemp()
    }
  }
}
</script>
<style lang="scss" scoped>

</style>